/* eslint-disable camelcase */
/* eslint-disable no-console */

const fs = require('fs');
const path = require('path');
const archiver = require('archiver');

const zipName = {
    test: 'BM_zhongbao_test.zip',
    uat: 'BM_zhongbao_uat.zip',
    prod: 'BM_zhongbao_prod.zip',
    staging: 'BM_zhongbao_staging.zip',
};

const { BUILD_ENV, ZIP_FILE_NAME } = process.env;
let zipFileName = '';

if (ZIP_FILE_NAME) {
    const hasExtension = ZIP_FILE_NAME.endsWith('.zip');
    zipFileName = `${ZIP_FILE_NAME}${hasExtension ? '' : '.zip'}`;
} else {
    zipFileName = zipName[BUILD_ENV] || 'error.zip';
}

console.error('　　', zipFileName);
fs.exists(zipFileName, async exists => {
    if (exists) {
        await fs.unlink(zipFileName, err => {
            if (err) throw err;
        });
    }

    const archiveFileName = path.join(__dirname, zipFileName);
    const output = fs.createWriteStream(archiveFileName);
    const archive = archiver('zip', {
        zlib: { level: 9 },
    });

    output.on('close', () => {
        console.log('　　', `${archive.pointer()} total bytes`);
        console.log('　　', `${archive.pointer() / 1024} kb`);
        console.log('archiver has been finalized and the output file descriptor has closed.');
    });

    archive.on('error', err => {
        throw err;
    });

    archive.pipe(output);

    archive.directory('./dist/', '');

    archive.finalize();
});